package com.zsoft.webmail.servlet.hainannet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.zsoft.webmail.*;
import com.zsoft.webmail.message.*;
import com.zsoft.webmail.folder.*;
import comm.http.upload.SmartUpload;
import com.zsoft.webmail.Application;

public class MailAttachmentAddServlet extends HttpServlet {
  //private static final String CONTENT_TYPE = Application.getProperty("ContentType");
  private static final String CONTENT_TYPE = "text/html";
  /**Initialize global variables*/
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/

  public void doGet1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    comm.http.Request request1=new comm.http.Request(request,Application.getProperty("defaultInputCharset"));

    //PrintWriter out = response.getWriter();
    String mimeCharset1=Application.getProperty("defaultMimeCharset");
    if(mimeCharset1==null || mimeCharset1.equals(""))
    mimeCharset1 = com.zsoft.webmail.mimeutility.MimeUtility.mimeCharset(com.zsoft.webmail.mimeutility.MimeUtility.getDefaultJavaCharset());
    String javaCharset1=com.zsoft.webmail.mimeutility.MimeUtility.javaCharset(mimeCharset1);
    comm.http.ResponseOut out= new comm.http.ResponseOut(response,javaCharset1,false);


    MemberAuthorization memberAuthToken=null ;
    HttpSession session=request.getSession();
    Object object = session.getAttribute("authBean");
    if(object==null){
      session.setAttribute("authBean",new com.zsoft.webmail.AuthBean(session.getId(),request.getRemoteAddr()));
      response.sendRedirect( "login.jsp" );
      return;
    }else{
      memberAuthToken = ((AuthBean)object).getMemberAuthToken();
      if(memberAuthToken==null){
        response.sendRedirect( "login.jsp" );
        return;
      }
    }

        SmartUpload attachment =new SmartUpload();


	// Variables
	int count=0;

	// Initialization
	attachment.initialize(super.getServletConfig(),request,response);


	// set the max file size
	//attachment.setMaxFileSize(10000000);

	// Upload
        try{
	attachment.upload();
        }catch(Exception e){
        }

        //if(true)return;
        String rn=attachment.getRequest().getParameter("rn");
	try {
		char sep='/';

		String uploadDir=memberAuthToken.webPath+sep+"upload"+sep;

		comm.http.upload.File myFile = attachment.getFiles().getFile(0);

		String uploadfn=rn+"."+myFile.getFileName();


		String ext=myFile.getFileExt();
		String fn=rn+"."+myFile.getFileName().substring( 0, myFile.getFileName().length()-ext.length()-1 );

		try
		{
			java.io.File file=new java.io.File(uploadDir+uploadfn);

			for (int i=1; file.exists(); i++)
			{
				uploadfn = fn + "(" + String.valueOf(i) + ")." + ext;
				file = new java.io.File(uploadDir+uploadfn);
                                //((AuthBean)object).getLog().err(uploadfn);
                                //System.err.println(uploadfn);
			}

		}
		catch (Exception e)
		{
			out.println(e.toString());
		}

		myFile.saveAs(uploadDir+uploadfn);
                //out.println(uploadDir+uploadfn);
	} catch (Exception e) {
		//out.println(e.toString());
	}

        response.sendRedirect("MailAttachment?rn="+rn);

  }


  private String getFileExt(String fileName)
  {
      String value = new String();
      int start = 0;
      int end = 0;
      if(fileName == null)
          return null;
      start = fileName.lastIndexOf(46) + 1;
      end = fileName.length();
      value = fileName.substring(start, end);
      if(fileName.lastIndexOf(46) > 0)
          return value;
      else
          return "";
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    comm.http.Request request1=new comm.http.Request(request,Application.getProperty("defaultInputCharset"));

    //PrintWriter out = response.getWriter();
    String mimeCharset1=Application.getProperty("defaultMimeCharset");
    if(mimeCharset1==null || mimeCharset1.equals(""))
    mimeCharset1 = com.zsoft.webmail.mimeutility.MimeUtility.mimeCharset(com.zsoft.webmail.mimeutility.MimeUtility.getDefaultJavaCharset());
    String javaCharset1=com.zsoft.webmail.mimeutility.MimeUtility.javaCharset(mimeCharset1);
    comm.http.ResponseOut out= new comm.http.ResponseOut(response,javaCharset1,false);


    MemberAuthorization memberAuthToken=null ;
    HttpSession session=request.getSession();
    Object object = session.getAttribute("authBean");
    if(object==null){
      session.setAttribute("authBean",new com.zsoft.webmail.AuthBean(session.getId(),request.getRemoteAddr()));
      response.sendRedirect( "login.jsp" );
      return;
    }else{
      memberAuthToken = ((AuthBean)object).getMemberAuthToken();
      if(memberAuthToken==null){
        response.sendRedirect( "login.jsp" );
        return;
      }
    }



        //if(true)return;
        String rn=request1.getParameter("rn");
        if(rn==null) {
          out.print("error");
          return;
        }
        for(int ii=1;ii<=5;ii++){


          String name=request1.getParameter("upload"+ii);

          String file1=request1.getParameter("upload"+ii+".file");


          String filename=request1.getParameter("upload"+ii+".filename");

          if(filename==null || filename.equals("") ) continue;
          //out.println(filename);

          String contentType=request1.getParameter("upload"+ii+".content-type");


          if(file1!=null){
            if(filename==null) {filename=comm.util.FileUtils.getFilename(file1);}
            else{
              filename=comm.util.FileUtils.getFilename(filename);
            }

            try {
                    char sep='/';

                    String uploadDir=memberAuthToken.webPath+sep+"upload"+sep;

                    java.io.File myFile = new java.io.File(file1);

                    String uploadfn=rn+"."+filename;


                    String ext=null;
                    String fn="";
                    int j=filename.lastIndexOf(".");
                    if(j>=0){
                      ext=filename.substring(j+1);
                      fn=rn+"."+filename.substring(0,j) ;
                    }else{
                      fn=rn+"."+filename;
                    }

                    java.io.File file=new java.io.File(uploadDir+uploadfn);

                    try
                    {


                            for (int i=1; file.exists(); i++)
                            {
                                    if(ext==null ){
                                      uploadfn = fn + "(" + String.valueOf(i) + ")";
                                    }else{
                                      uploadfn = fn + "(" + String.valueOf(i) + ")." + ext;
                                    }
                                    file = new java.io.File(uploadDir+uploadfn);
                                    //((AuthBean)object).getLog().err(uploadfn);
                                    //System.err.println(uploadfn);
                            }

                    }
                    catch (Exception e)
                    {
                            //out.println(e.toString());
                    }

                    comm.util.FileUtils.copyFile(myFile,file);

                    //myFile.saveAs(uploadDir+uploadfn);
                    //out.println(uploadDir+uploadfn);
            } catch (Exception e) {
                    //out.println(e.toString());
            }
          }

        }

        out.println("<script>");
        out.print("document.location.href='attachment.jsp?rn="+rn+"'");
        out.println("</script>");
        //response.sendRedirect("attachment.jsp?rn="+rn);

  }
  /**Process the HTTP Post request*/
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
  }
  /**Clean up resources*/
  public void destroy() {
  }
}